<?php

App::uses('AppModel', 'Model');

/**
 * ModuleSmsBroadcastListContact Model
 *
 * @property ModuleSmsBroadcastList $ModuleSmsBroadcastList
 * @property Member $Member
 */
class ModuleSmsBroadcastListContact extends AppModel {

    /**
     * Use database config
     *
     * @var string
     */
    public $useDbConfig = 'organisations';

    /**
     * Display field
     *
     * @var string
     */
    public $displayField = 'name';


    //The Associations below have been created with all possible keys, those that are not needed can be removed

    /**
     * belongsTo associations
     *
     * @var array
     */
    public $belongsTo = array(
        'ModuleSmsBroadcastList' => array(
            'className' => 'ModuleSmsBroadcastList',
            'foreignKey' => 'module_sms_broadcast_list_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'Member' => array(
            'className' => 'Member',
            'foreignKey' => 'member_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );
    
    public function addContact($organisation_id, $broadcast_list_id, $member_id) {
        $broadcast_list =  $this->ModuleSmsBroadcastList->find('first', array(
            'conditions' => array(
                'ModuleSmsBroadcastList.organisation_id' => $organisation_id,
                'ModuleSmsBroadcastList.id' => $broadcast_list_id
            ),
            'recursive' => -1
        ));
        
        if( !$broadcast_list ) {
            return array('status' => 'failed', 'message' => 'Broadcast list specified is not valid');
        }
        
        $org_member = ClassRegistry::init('OrganisationMember')->getAssociation($organisation_id, $member_id);
        
        if( !$org_member ) {
            return array('status' => 'failed', 'message' => 'Specified member does not belong to specified organisation');
        }
        
        $data = $this->save(array(
            'module_sms_broadcast_list_id' => $broadcast_list_id,
            'member_id' => $member_id,
            'name' => $org_member['Member']['full_name'],
            'number' => $org_member['Member']['mobile_number']
        ));
        
        $contact_id = $this->id;
        
        return array('status' => 'success', 'message' => 'Contact added successfully', 'broadcast_list_contact_id' => $contact_id);
    }

}
